package com.dd.common.utils;

import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求上下文工具类
 * 获取当前请求的上下文、URL、域名、端口、设备类型、请求方式等
 **/
public class RequestContextUtils {

    private static final String HEADER_X_FORWARDED_PROTO = "X-Forwarded-Proto";
    private static final String HEADER_X_FORWARDED_HOST = "X-Forwarded-Host";
    private static final String HEADER_HOST = "Host";
    private static final String HEADER_USER_AGENT = "User-Agent";

    private static final int PORT_HTTP = 80;
    private static final int PORT_HTTPS = 443;

    /**
     * 获取当前请求的 HttpServletRequest 对象
     *
     * @return HttpServletRequest 或 null（不在请求线程中）
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    /**
     * 获取 User-Agent 解析结果
     *
     * @return UserAgent 解析结果
     */
    public static UserAgent getUserAgent() {
        HttpServletRequest request = getRequest();
        return request != null ? UserAgent.parseUserAgentString(request.getHeader(HEADER_USER_AGENT)) : null;
    }


    /**
     * 获取不带参数的完整请求 URL
     * 示例: https://127.0.0.1:8082/api/system/menu/menus
     *
     * @return 完整 URL，无则返回空字符串
     */
    public static String url() {
        HttpServletRequest request = getRequest();
        return request != null ? request.getRequestURL().toString() : "";
    }

    /**
     * 获取请求路由（不包含协议、主机、端口）
     * 示例: /api/system/menu/menus
     *
     * @return 路由路径，无则返回空字符串
     */
    public static String route() {
        HttpServletRequest request = getRequest();
        return request != null ? request.getRequestURI() : "";
    }

    /**
     * 获取请求端口
     * 示例: 8080, 443, 80
     *
     * @return 端口号，无则返回 0
     */
    public static Integer port() {
        HttpServletRequest request = getRequest();
        return request != null ? request.getServerPort() : 0;
    }

    /**
     * 判断当前请求是否为 HTTPS
     *
     * @return true 表示 HTTPS
     */
    private static boolean isSecure() {
        HttpServletRequest request = getRequest();
        if (request == null) return false;

        // 优先检查反向代理头
        String forwardedProto = request.getHeader(HEADER_X_FORWARDED_PROTO);
        if ("https".equalsIgnoreCase(forwardedProto)) {
            return true;
        }

        // 检查原始请求协议
        return "https".equalsIgnoreCase(request.getScheme()) || request.isSecure();
    }

    /**
     * 获取协议 + 域名（不带端口）
     * 示例: https://127.0.0.1
     *
     * @return 协议 + 域名，无则返回 null
     */
    public static String domain() {
        HttpServletRequest request = getRequest();
        if (request == null) return null;

        // 使用 getServerName() 更安全，避免解析 URL 出错
        String host = request.getServerName();

        // 优先从反向代理头获取协议
        boolean isSecure = isSecure();
        String protocol = isSecure ? "https" : "http";

        return protocol + "://" + host;
    }

    /**
     * 获取协议 + 域名 + 端口（如果非标准端口）
     * 示例: https://127.0.0.1:8082
     *
     * @return 完整地址
     */
    public static String uri() {
        String domain = domain();
        if (domain == null) return "";

        int port = port();
        // 非标准端口才附加
        if (port != PORT_HTTP && port != PORT_HTTPS && port != 0) {
            return domain + ":" + port;
        }

        return domain;
    }

    /**
     * 获取设备类型（Android / IOS / wap）
     *
     * @return 设备标识
     */
    public static String device() {
        HttpServletRequest request = getRequest();
        if (request == null) return "wap";

        String userAgent = request.getHeader(HEADER_USER_AGENT);
        if (userAgent == null || userAgent.isEmpty()) {
            return "wap";
        }

        userAgent = userAgent.toLowerCase();

        if (userAgent.contains("android")) {
            return "Android";
        } else if (userAgent.contains("iphone") ||
                userAgent.contains("ipod") ||
                userAgent.contains("ipad")) {
            return "IOS";
        } else {
            return "wap"; // PC 或其他
        }
    }

    /**
     * 判断是否为 GET 请求
     */
    public static boolean isGet() {
        return "GET".equalsIgnoreCase(method());
    }

    /**
     * 判断是否为 POST 请求
     */
    public static boolean isPost() {
        return "POST".equalsIgnoreCase(method());
    }

    /**
     * 判断是否为 PUT 请求
     */
    public static boolean isPut() {
        return "PUT".equalsIgnoreCase(method());
    }

    /**
     * 判断是否为 DELETE 请求
     */
    public static boolean isDelete() {
        return "DELETE".equalsIgnoreCase(method());
    }

    /**
     * 获取请求方法（GET/POST/PUT/DELETE）
     *
     * @return 方法名，无则返回空字符串
     */
    private static String method() {
        HttpServletRequest request = getRequest();
        return request != null ? request.getMethod() : "";
    }
}
